import { DatasetTypeEnum, GetDatasetList, GetDatasetNl2sqlList, GetTargetTreeResources } from '@/common/types';
import { Button, Empty } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import ModalsBoxContent from '@/components/modals/ModalsBoxContent';
import { CaretDownOutlined } from '@ant-design/icons';
import { Checkbox, Tooltip } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';

interface Props {
  list: GetDatasetList[] | GetDatasetNl2sqlList[];
  selectKnow?: GetTargetTreeResources[];
  handleClickKnow: (type: string, know?: GetDatasetList) => void;
  tabsKey: string;
  handleClickTreeUITree: (value: GetDatasetList) => void;
  expandedKeys: string[];
  treeUIRef: React.RefObject<HTMLDivElement>;
  handleTreeUIOpen: () => void;
  openStatus: boolean;
  contentHeight?: string;
}

const TreeUI = ({
  list,
  selectKnow,
  handleClickKnow,
  tabsKey,
  handleClickTreeUITree,
  expandedKeys,
  treeUIRef,
  handleTreeUIOpen,
  openStatus,
  contentHeight,
}: Props) => {
  const know = useMemo(
    () =>
      selectKnow?.find(
        (item) =>
          (item.resource_type === (tabsKey === '1' ? DatasetTypeEnum.dataset : tabsKey === '2' ? DatasetTypeEnum.function : DatasetTypeEnum.database) &&
            item.resource_id === '*') ||
          (item.resource_type === '*' && item.resource_id === '*'),
      ),
    [selectKnow, tabsKey],
  );

  const navigate = useNavigate();
  const handleClick = (routerPath: string) => {
    // 解析 search 参数
    const searchParams = new URLSearchParams(location.search);

    // 移除所有 app 参数
    searchParams.delete('app');

    // 添加新的 app 参数
    searchParams.append('app', routerPath);

    // 如果有 currentTab 字段，改为 knowledge
    if (searchParams.has('currentTab')) {
      searchParams.set('currentTab', 'knowledge');
    }

    // 重新拼接 search 字符串
    const newSearch = `?${searchParams.toString()}`;

    // 拼接新地址
    const newPath = `${location.pathname.replace(/\/$/, '')}${newSearch}`;
    navigate(newPath);
  };

  return (
    <div>
      <div className="mr-6 flex h-10 bg-fill-1 text-cn-14-blod leading-10 text-text-3">
        <div className="flex w-1/2 items-center gap-2 pl-3">
          <div>{tabsKey === '1' ? '知识库名称' : tabsKey === '2' ? '数据接口名称' : '数据库问答'}</div>
          {tabsKey === '1' && (
            <Tooltip title={openStatus ? '关闭文件夹' : '展开文件夹'}>
              <div>
                <SvgIcon
                  icon={openStatus ? 'node-close' : 'node-open'}
                  size="16px"
                  className="rotate-90 cursor-pointer"
                  onClick={handleTreeUIOpen}
                />
              </div>
            </Tooltip>
          )}
        </div>
        <div className="w-1/2 text-center">
          <Checkbox checked={know !== undefined} onClick={() => handleClickKnow('all')}>
            问答权限
          </Checkbox>
        </div>
      </div>
      <ModalsBoxContent
        className="overflow-y-auto"
        ref={treeUIRef}
        style={{
          height: `calc(100vh - ${contentHeight})`,
          // height: 'calc(100vh - 396px)',
        }}
      >
        {list.map((dataset) => (
          <TreeNode
            node={dataset}
            key={dataset._id}
            know={know !== undefined}
            selectKnow={selectKnow}
            handleClickKnow={handleClickKnow}
            handleClickTreeUITree={handleClickTreeUITree}
            expandedKeys={expandedKeys}
          />
        ))}
        {list?.length === 0 && (
          <div className="flex h-1/2 flex-col items-center justify-end">
            <Empty fontText="暂无数据" className="!justify-end mb-4"/>
            <div>
              <Button type="secondary" onClick={() => {handleClick(tabsKey === '1' ? 'datasets' : tabsKey === '2' ? 'api' : 'nl2sql')}}>立即添加</Button>
            </div>
          </div>
        )}
      </ModalsBoxContent>
    </div>
  );
};

interface TreeNodeProps {
  node: GetDatasetList;
  level?: number;
  know?: boolean;
  parentSelect?: boolean;
  selectKnow?: GetTargetTreeResources[];
  handleClickKnow: (type: string, know?: GetDatasetList) => void;
  handleClickTreeUITree: (value: GetDatasetList) => void;
  expandedKeys: string[];
}

const TreeNode = ({
  node,
  level = 0,
  know,
  selectKnow,
  handleClickKnow,
  parentSelect = false,
  handleClickTreeUITree,
  expandedKeys,
}: TreeNodeProps) => {
  // const [expanded, setExpanded] = useState(true);

  const expanded = useMemo(() => {
    return expandedKeys.includes(node._id);
  }, [expandedKeys]);

  const icon = useMemo(() => {
    if (node.type === 'function') {
      return {
        icon: 'file-api',
        color: '#33ADFF',
      };
    } else if (node.type === 'folder') {
      return {
        icon: 'folder-svg',
        color: '#FECA27',
      };
    } else {
      return {
        icon: 'dataset',
        color: '#4172FE',
      };
    }
  }, [node]);

  const select = useMemo(() => {
    return selectKnow?.find((item) => item.resource_id === node._id);
  }, [selectKnow, node]);

  return (
    <>
      <div
        data-id={node._id}
        className="flex h-10 border-b-[1px] border-solid border-b-line-1 text-cn-14 leading-10 text-[#1d1d1d]"
      >
        <div
          className="flex w-1/2 items-center gap-2"
          style={{
            paddingLeft: level * 12,
          }}
        >
          <div className="flex h-6 w-6 items-center justify-center font-medium">
            {node.type === 'folder' && node.children?.length > 0 && (
              <CaretDownOutlined
                onClick={() => handleClickTreeUITree(node)}
                rotate={expanded ? 0 : -90}
              />
            )}
          </div>
          <SvgIcon icon={icon.icon} color={icon.color} size={24} />
          <div>{node.name}</div>
          {node?.children?.length > 0 && node.type === 'folder' && (
            <div>({node?.children?.length})</div>
          )}
        </div>
        <div className="w-1/2 text-center">
          <Checkbox
            checked={parentSelect || know || select !== undefined}
            onClick={() => handleClickKnow('type', node)}
          >
            问答
          </Checkbox>
        </div>
      </div>

      {expanded &&
        node.children &&
        node.children.map((child) => (
          <TreeNode
            node={child}
            key={child._id}
            level={level + 1}
            know={know}
            handleClickKnow={handleClickKnow}
            selectKnow={selectKnow}
            parentSelect={parentSelect || select !== undefined}
            handleClickTreeUITree={handleClickTreeUITree}
            expandedKeys={expandedKeys}
          />
        ))}
    </>
  );
};

export default TreeUI;
